package cn.cxyxj.code_auth_jwt_persistence_prod.auth.handler;


import cn.cxyxj.code_auth_jwt_persistence_prod.common.ApiResult;
import com.alibaba.fastjson.JSON;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 登录异常回调
 */
public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException {

        resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
        PrintWriter out = resp.getWriter();
        String msg = "";
        if (e instanceof LockedException) {
            msg = "账户被锁定，请联系管理员!";
        }
        if (e instanceof DisabledException) {
            msg = "账户未启用，请联系管理员!";
        } else if (e instanceof BadCredentialsException) {

            msg = "用户密码输入错误，请重新输入!";
        }
        else if (e instanceof AuthenticationServiceException) {
            msg = e.getMessage();
        }
        out.write(JSON.toJSONString(ApiResult.fail(msg)));
        out.flush();
        out.close();
    }
}
